// https://leetcode.cn/problems/sort-list/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* ta, ListNode* tb) {
        // ListNode* ta;
        // ListNode* tb;
        ListNode* dummy = new ListNode(-1);
        ListNode* tmp = dummy;
        while (ta && tb) {
            if (ta->val < tb->val) {
                tmp->next = ta;
                ta = ta->next;
            } else {
                tmp->next = tb;
                tb = tb->next;
            }
            tmp = tmp->next;
        }
        if (ta) tmp->next = ta;
        if (tb) tmp->next = tb;
        return dummy->next;
    }
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) 
            // return NULL; 注意！！
            return head;
        ListNode* fast = head->next;
        ListNode* slow = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode* mid = slow->next;
        slow->next = NULL;
        ListNode* left = sortList(head);
        ListNode* right = sortList(mid);
        return merge(left, right);
    }
};